setwd(normalizePath(dirname(R.utils::commandArgs(asValues=TRUE)$"f")))
source("../../scripts/h2o-r-test-setup.R")
if ("slam" %in% rownames(installed.packages()))
  library(slam)
if ("data.table" %in% rownames(installed.packages()))
  library(data.table)

# In PUBDEV-4630: it was complaint by some users that as.h2o is very slow with spare matrices.  Hence,
# Peter Ellis suggested a fix for this.  His fix fixed the speed problem but was generating wrong answers.
# For rows with all zeros, he will replace it another row instead of generating a row of zeros.  I fixed
# this.  In this test, I will compare as.h2o with his fix and my fix with answers generated by original 
# as.h2o using randomly generated sparse matrices.

check.as.h2o <- function() {
# work with randomly generated matrices and check frames generated with new and original as.h2o agree.
  if (("slam" %in% rownames(installed.packages()))&&("data.table" %in% rownames(installed.packages()))) {

    print("******  Running random matrix test to check execution time...")
    nRow <- 90000
    nCol <- 1000
    probOne <- 0.001   # generate sparse matrix here
    m <- matrix(rbinom(nRow*nCol, 1, probOne), ncol = nCol)
    sparseM <- Matrix(m, sparse=TRUE)# convert matrix to sparse matrix
    print("Time taking to convert sparse matrix using as.h2o is ")
    options("h2o.use.data.table"=TRUE)
    ptm <- proc.time()
    dr2h2oD <- as.h2o(sparseM, destination_frame="new_as_h2o")
    timepassedD <- proc.time()-ptm
    print(timepassedD)
    print("Time taking to convert sparse matrix using as.h2o slow is ")
    options("h2o.use.data.table"=FALSE)
    ptm <- proc.time()
    expect_warning(dr2h2oD2 <<- as.h2o(sparseM, destination_frame="old_as_h2o"))
    timepassedD <- proc.time()-ptm
    print(timepassedD)
    compare_frames(dr2h2oD, dr2h2oD2, 50)# only check 10 random elements, takes forever
    h2o.removeAll()
  } else {
    print("PUBDEV-4630: as.h2o slow with sparse matrices test is skipped due to slam or data.table packages missing.")
  }
}

compare_frames <- function(f1, f2, number2Comp) {
  expect_equal(ncol(f1), ncol(f2))
  expect_equal(nrow(f1), nrow(f2))

  col_ind <- sample(c(1:ncol(f1)), min(number2Comp, ncol(f1)))
  row_ind <- sample(c(1:nrow(f1)), min(number2Comp, nrow(f1)))
  all_index = paste(c(1:number2Comp), row_ind, col_ind)

  for (index in c(1:number2Comp)) {
      indices = strsplit(all_index[index], " ")
      rowInd = as.numeric(indices[[1]][2])
      colInd = as.numeric(indices[[1]][3])
      expect_equal(f1[rowInd, colInd], f2[rowInd, colInd])
  }
}

doTest("PUBDEV-4630: as.h2o slow with sparse matrices.", check.as.h2o)